package com.fs.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


//把这个工具类交给IDC容器进行管理
@Component //因为这个类不属于三层架构所以用@Component注解进行注解,交给IOC容器进行管理
public class AliOSSUtils {
   /* @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    // 填写Bucket名称，例如examplebucket。
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;*/

    /*
     * 上传图片到oos
     * */
    //注入oss参数配置管理类
    @Autowired
    private AliOSSProperties aliOSSProperties;
    public String upload(MultipartFile file) throws IOException {
        //获取阿里云oss的相关的参数
        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();
        //获取上传文件的输入流
        InputStream inputStream = file.getInputStream();

        //获取要上传文件的名字
        String originalFilename = file.getOriginalFilename();
        //创建文件的唯一标识码
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到oos
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, filename, inputStream);

        //获取文件访问的路径

        //https://web-fs.oss-cn-hangzhou.aliyuncs.com/fa2a09c9-fbc7-4555-828f-1c74a78761f1.png
        //"https://web-fs.oss-cn-hangzhou.aliyuncs.com/36.png"
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename;
        //关闭链接
        ossClient.shutdown();
        return url;
    }
} 